import { debounce } from 'lodash'
import config from '@/requests/config'
import { baseUrl } from '@/config'

const interceptor = {
  invoke(args : any) {
    //拦截前触发  请求拦截器
    const token = uni.getStorageSync('token') || '' //拿到存储的token
    args.header = {
      Authorization: `Bearer ${token}`,
    }
  },
}

//拦截请求
uni.addInterceptor('request', interceptor)
uni.addInterceptor('uploadFile', interceptor)

//拦截响应
export default (method : any, url : any, data ?: any, options ?: any) => {
  const token = uni.getStorageSync('token') || '' //拿到存储的token
  const url_ = `${baseUrl}${url}`
  const storeInfo = uni.getStorageSync('storeInfo') || ''
  console.log(storeInfo, 'storeInfo')
  // 判断条件：storeInfo有值 且 data中不存在deptId字段
  if (storeInfo&& options != 'no') {
    const tempData = data || {};
    if (!('deptId' in tempData)) {
      data = {
        ...tempData,
        deptId: storeInfo.deptId
      };
    }
  }
  if (options !== 'UPLOAD') {
    return new Promise((resolve, reject) => {
      uni.request({
        ...config,
        method,
        url: url_,
        data,
        ...options,
        success(res : any) {
          console.log(res, "resresres")
          if (res.statusCode !== 200) {
            showErr(`系统错误：${res.statusCode}`)
          } else {
            if (res?.data?.code + '' === '200') {
              resolve(res.data)
              return
            }
            if (res?.data?.code + '' === '500') {
              showErr(res?.data?.msg)
              return
            }
            if (res?.data?.code + '' === '401') {
              showErr(res?.data?.msg)
              setTimeout(() => {
                uni.reLaunch({ url: '/pages/login/index' })
              }, 1000)
            } else if (res?.data?.ResponseCode + '' !== '1') {
              showErr(res?.data?.msg)
            }
            resolve(res.data)
          }
        },
      })
    })
  } else {
    return new Promise((resolve, reject) => {
      console.log(data, '11111111')
      uni.uploadFile({
        ...config,
        url: url_,
        filePath: data.url,
        name: 'file',
        ...options,
        success(res : any) {
          resolve(JSON.parse(res.data))
        },
      })
    })
  }
}

// 报错加个debounce
const showErr = debounce((msg : any) => {
  uni.showToast({
    title: msg || "",
    icon: 'none',
  })
}, 200)
